package org.dreamwork.tools.network.bridge.client.fx.views;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import org.dreamwork.network.service.ServiceFactory;
import org.dreamwork.tools.network.bridge.client.data.Proxy;
import org.dreamwork.tools.network.bridge.client.data.Server;
import org.dreamwork.tools.network.bridge.client.fx.GuiContext;
import org.dreamwork.tools.network.bridge.client.services.IClientMonitorService;
import org.dreamwork.tools.network.bridge.client.services.IClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by seth.yang on 2020/3/11
 */
public class ProxyView extends HBox implements Initializable {
    @FXML private Label tunnelName;
    @FXML private Label route;
    @FXML private ImageView icon;

    private final Proxy proxy;
    private final Logger logger = LoggerFactory.getLogger (ProxyView.class);

    public ProxyView (Proxy proxy) {
        this.proxy = proxy;

        FXMLLoader loader = new FXMLLoader (getClass ().getClassLoader ().getResource ("jfx/proxy.fxml"));
        loader.setRoot (this);
        loader.setController (this);
        try {
            loader.setResources (GuiContext.ui);
            loader.load ();
        } catch (Exception ex) {
            logger.warn (ex.getMessage (), ex);
        }
    }

    @Override
    public void initialize (URL location, ResourceBundle resources) {
        tunnelName.setText (proxy.name);

        IClientMonitorService monitor = ServiceFactory.get (IClientMonitorService.class);
        if (monitor.containsClient (proxy.name)) {
            icon.setImage (new Image ("images/64x64/exchange-connected.png"));
        } else {
            icon.setImage (new Image ("images/64x64/exchange.png"));
        }

        IClientService service = ServiceFactory.get (IClientService.class);
        Server server = service.get (proxy.server);
        String label = server.getHost () + ':' + proxy.servicePort +
                " <=> " +
                proxy.peer + ':' + proxy.peerPort;
        route.setText (label);
    }
}